import React from 'react';

import router from 'umi/router';

import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import { MuiThemeProvider } from '@material-ui/core/styles';
import { withStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import LinearProgress from '@material-ui/core/LinearProgress';
import Visibility from '@material-ui/icons/Visibility';
import VisibilityOff from '@material-ui/icons/VisibilityOff';
import IconButton from '@material-ui/core/IconButton';
import Input from '@material-ui/core/Input';
import InputLabel from '@material-ui/core/InputLabel';
import InputAdornment from '@material-ui/core/InputAdornment';
import FormControl from '@material-ui/core/FormControl';

import request from '../../utils/request';
import { setPSITokenId, getPSITokenId } from '../../utils/tokenId';
import MsgBox from '../../utils/msgbox';
import mainTheme from '../../theme/mainTheme';

const styles = theme => ({
  root: {
    flexGrow: 1,
    height: '100%'
  },
  loginForm: {
    margin: 20
  },
  loginButton: {
    margin: 20
  }
});

/**
 * 登录页面
 */
class LoginPage extends React.Component {
  state = {
    loginName: '',
    password: '',
    demoInfo: '',
    msgBoxOpen: false,
    msgBoxInfo: '',
    loading: true,
    showPassword: false,
    autoLogin: false
  }

  componentDidMount = () => {
    let loginName = localStorage.getItem('PSI_loginName');
    if (loginName === null) {
      loginName = '';
    }
    let password = localStorage.getItem('PSI_password');
    if (password === null) {
      password = '';
    }
    this.setState({
      loginName,
    });

    // 查询演示版的提示信息
    request('/web/API/User/getDemoLoginInfo', {
      method: "POST",
      body: new FormData(),
    }).then(({ data }) => {
      this.setState({ demoInfo: data.msg, loading: false });
    });

    // 自动登录
    if (loginName && password) {
      this.setState({ autoLogin: true });

      var formData = new FormData();
      formData.append("loginName", loginName);
      formData.append("password", password);

      // 延迟半秒后执行自动登录，仅仅是为了增加用户视觉效果
      setTimeout(() => {
        request('/web/API/User/doLogin', {
          credentials: 'include',
          method: "POST",
          body: formData,
        }).then(({ data }) => {
          if (data.success) {
            // 自动登录成功
            setPSITokenId(data.tokenId);

            localStorage.setItem('PSI_loginName', loginName);
            localStorage.setItem('PSI_password', password);

            router.replace('/');
          } else {
            // 自动登陆失败
            this.setState({ autoLogin: false });
          }
        });
      }, 500);
    }
  }

  render() {
    if (getPSITokenId()) {
      router.replace('/');
    }

    const { classes } = this.props;
    const { loading, autoLogin, msgBoxInfo, msgBoxOpen } = this.state;

    return (
      <MuiThemeProvider theme={mainTheme}>
        <CssBaseline />
        <AppBar position="static">
          <Toolbar>
            <Typography variant="title" color="inherit">
              PSI
          </Typography>
          </Toolbar>
        </AppBar>
        <LinearProgress color='secondary' hidden={!loading && !autoLogin} />
        {autoLogin && <h1>自动登录中......</h1>}
        {!autoLogin && <>
          <form noValidate autoComplete="off" className={classes.loginForm}>
            <TextField
              id="name"
              label="登录名"
              margin="normal"
              fullWidth
              type='text'
              value={this.state.loginName}
              onChange={(e) => { this.setState({ loginName: e.target.value }) }}
            />
            <FormControl fullWidth>
              <InputLabel>密码</InputLabel>
              <Input
                type={this.state.showPassword ? 'text' : 'password'}
                value={this.state.password}
                onChange={(e) => { this.setState({ password: e.target.value }) }}
                endAdornment={
                  <InputAdornment position="end">
                    <IconButton
                      onClick={() => { this.setState({ showPassword: !this.state.showPassword }); }}
                    >
                      {this.state.showPassword ? <VisibilityOff /> : <Visibility />}
                    </IconButton>
                  </InputAdornment>
                }
              />
            </FormControl>
          </form>

          <div className={classes.loginButton}>
            <Button variant="raised" color="primary" size='large' fullWidth
              onClick={this.doLogin} >
              登录
          </Button>
          </div>
          <div style={{ margin: 20 }} hidden={!this.state.demoInfo}>{this.state.demoInfo}</div>
        </>
        }

        <MsgBox open={msgBoxOpen} info={msgBoxInfo}
          onOK={() => { this.setState({ msgBoxOpen: false }) }}>
        </MsgBox>
      </MuiThemeProvider>
    );
  }

  /**
   * 执行登录操作
   */
  doLogin = () => {
    const { loginName, password } = this.state;
    if (!loginName) {
      this.setState({
        msgBoxOpen: true,
        msgBoxInfo: '没有输入登录名'
      });
      return;
    }
    if (!password) {
      this.setState({
        msgBoxOpen: true,
        msgBoxInfo: '没有输入登录密码'
      });
      return;
    }

    this.setState({
      loading: true
    });

    var formData = new FormData();
    formData.append("loginName", loginName);
    formData.append("password", password);

    request('/web/API/User/doLogin', {
      credentials: 'include',
      method: "POST",
      body: formData,
    }).then(({ data }) => {
      if (data.success) {
        // 登录成功
        setPSITokenId(data.tokenId);

        localStorage.setItem('PSI_loginName', loginName);
        localStorage.setItem('PSI_password', password);

        router.replace('/');
      } else {
        // 登录失败，显示错误信息
        this.setState({
          msgBoxOpen: true,
          loading: false,
          msgBoxInfo: data.msg
        });
      }
    });
  }
};

LoginPage.propTypes = {
};

export default withStyles(styles)(LoginPage);
